<?php

namespace App\Store\Services;

use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Financial\Statements\Moneylog;
use App\Store\Models\Financial\Statements\Rate;

class Financial
{
    public static function getFeeByMoney($cp_id, $store_id, $money, $pay_type_id)
    {
        $rateinfo = Rate::where(['cp_id' => $cp_id, 'store_id' => $store_id])->where([['money_start', '<=', $money], ['money_end', '>=', $money], ['pay_type_id', $pay_type_id], ['is_del', 1]])->first();
        if ($rateinfo) {
            if ($rateinfo->val_type == 1) {
                return $rateinfo->regular_value;
            } else {
                return ceil(bcmul($money, $rateinfo->rate_value, 2) / 100);
            }
        } else {
            return 0;
        }
    }

    protected static function getmoneylogcount($type, $receipt_type, $cp_id)
    {
        $log_date_s = date('Y-m') . '-01';
        $count = Moneylog::where([['cp_id', $cp_id], ['type', $type], ['receipt_type', $receipt_type], ['log_date', '>=', $log_date_s]])->count();
        $count += 1;
        return ['count' => $count, 'no' => date('n') . '-' . $count . '#'];
    }

    public static function createMoneyLog($cp_id, $order,$income_money, $subject_id = -1, $abstract = '销售明细')
    {
        $pay_type_id = $order->pay_type_id ?? 0;
        $sn_code = $order->order_sn ?? '';
        $store_id = $order->store_id ?? 0;
        $mixed_payment = $order->mixed_payment ?? [];

        $data = [
            'cp_id' => $cp_id,
            'store_id' => $store_id,
            'pay_type_id' => $pay_type_id,
            'income_money' => $income_money,
            'expenditure_money' => 0,
            'log_date' => date('Y-m-d'),
            'subject_id' => $subject_id,
            'create_at' => time(),
            'update_at' => time()
        ];
        $paytype = PaytypeList::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->get()
            ->pluck('paytype_name', 'id')
            ->toArray();

        if ($pay_type_id < 0 && !empty($mixed_payment)) {
            foreach ($mixed_payment as $key => $money) {
                $id = explode('_', $key)[1] ?? 0;
                if ($id > 0) {
                    $pay_type_name = $paytype[$id] ?? '';
                    $receipt = self::receiptType($pay_type_name);
                    $data['type'] = $receipt['type'];
                    $data['receipt_type'] = $receipt['receipt_type'];
                    $receipt_type_name = $receipt['receipt_type_name'];
                    // 混合支付拆分金额
                    $data['income_money'] = $money;
                    self::moneylogAdd($cp_id, $data, $store_id, $sn_code, $receipt_type_name, $money, $id);
                }
            }

        } else {
            $pay_type_name = $paytype[$pay_type_id] ?? '';
            $receipt = self::receiptType($pay_type_name);
            $data['type'] = $receipt['type'];
            $data['receipt_type'] = $receipt['receipt_type'];
            $receipt_type_name = $receipt['receipt_type_name'];
            // 其他支付
            self::moneylogAdd($cp_id, $data, $store_id, $sn_code, $receipt_type_name, $income_money, $pay_type_id);
        }
        return true;

    }

    public static function createMoneyLogByAuditCancel($cp_id,$info, $income_money=0, $subject_id = -1, $abstract = '销售明细')
    {
        $pay_type_id = $info->pay_type_id ?? 0;
        $sn_code = $info->order_sn ?? '';
        $store_id = $info->store_id ?? 0;
        $mixed_payment = $info->mixed_payment ?? [];

        $data = [
            'cp_id' => $cp_id,
            'store_id' => $store_id,
            'pay_type_id' => $pay_type_id,
            'income_money' => 0,
            'expenditure_money' => $income_money > 0 ? $income_money : 0,
            'log_date' => date('Y-m-d'),
            'subject_id' => $subject_id,
            'create_at' => time(),
            'update_at' => time()
        ];

        $paytype = PaytypeList::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->get()
            ->pluck('paytype_name', 'id')
            ->toArray();

        if ($pay_type_id < 0 && !empty($mixed_payment)) {
            // 如果有混合支付
            foreach ($mixed_payment as $key => $money) {
                $id = explode('_', $key)[1] ?? 0;
                if ($id > 0) {
                    $pay_type_name = $paytype[$id] ?? '';
                    $receipt = self::receiptType($pay_type_name);
                    $data['type'] = $receipt['type'];
                    $data['receipt_type'] = $receipt['receipt_type'];
                    $receipt_type_name = $receipt['receipt_type_name'];
                    $count_res = self::getmoneylogcount($data['type'], $data['receipt_type'], $cp_id);
                    $receipt_no = $receipt_type_name . $count_res['no'];

                    $data['issys'] = 2;
                    $data['abstract'] = $sn_code;
                    $data['receipt_no'] = $receipt_no;
                    $data['remark'] = '已审核订单撤审';
                    $data['inout_type'] = 1;
                    $last_moneylog = Moneylog::where(['type' => $data['type'], 'store_id' => $store_id, 'is_del' => 1])->orderBy('id', 'desc')->first();
                    $last_moneylog_residue_money = $last_moneylog ? $last_moneylog->residue_money : 0;
                    $data['residue_money'] = $last_moneylog_residue_money - $money;
                    Moneylog::create($data);
                }
            }

        }else{
            $pay_type_name = $paytype[$pay_type_id] ?? '';
            $receipt = self::receiptType($pay_type_name);
            $data['type'] = $receipt['type'];
            $data['receipt_type'] = $receipt['receipt_type'];
            $receipt_type_name = $receipt['receipt_type_name'];
            $count_res = self::getmoneylogcount($data['type'], $data['receipt_type'], $cp_id);
            $receipt_no = $receipt_type_name . $count_res['no'];

            $data['issys'] = 2;
            $data['abstract'] = $sn_code;
            $data['receipt_no'] = $receipt_no;
            $data['remark'] = '已审核订单撤审';
            $data['inout_type'] = 1;
            $last_moneylog = Moneylog::where(['type' => $data['type'], 'store_id' => $store_id, 'is_del' => 1])->orderBy('id', 'desc')->first();
            $last_moneylog_residue_money = $last_moneylog ? $last_moneylog->residue_money : 0;
            $data['residue_money'] = $last_moneylog_residue_money - $income_money;
            Moneylog::create($data);
        }
    }

    public static function createMoneyLogByPaymoney($cp_id, $store_id, $pay_type_id, $expenditure_money, $sn_code, $subject_id = -2,$mixed_payment=[], $abstract = '应付账款')
    {
        $data = [
            'cp_id' => $cp_id,
            'store_id' => $store_id,
            'pay_type_id' => $pay_type_id,
            'income_money' => 0,
            'expenditure_money' => $expenditure_money,
            'log_date' => date('Y-m-d'),
            'subject_id' => $subject_id,
            'create_at' => time(),
            'update_at' => time()
        ];

        $paytype = PaytypeList::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->get()
            ->pluck('paytype_name', 'id')
            ->toArray();
        if ($pay_type_id < 0 && !empty($mixed_payment)) {

            // 如果有混合支付
            foreach ($mixed_payment as $key => $money) {
                $id = explode('_', $key)[1] ?? 0;
                if ($id > 0) {
                    $pay_type_name = $paytype[$id] ?? '';
                    $receipt = self::receiptType($pay_type_name);
                    $data['type'] = $receipt['type'];
                    $data['receipt_type'] = $receipt['receipt_type'];
                    $receipt_type_name = $receipt['receipt_type_name'];
                    $count_res = self::getmoneylogcount($data['type'], $data['receipt_type'], $cp_id);
                    $receipt_no = $receipt_type_name . $count_res['no'];

                    $data['inout_type'] = 2;
                    $data['issys'] = 2;
                    $data['abstract'] = $sn_code;
                    $data['receipt_no'] = $receipt_no;
                    $last_moneylog = Moneylog::where(['type' => $data['type'], 'store_id' => $store_id, 'is_del' => 1])->orderBy('id', 'desc')->first();
                    $last_moneylog_residue_money = $last_moneylog ? $last_moneylog->residue_money : 0;
                    $data['residue_money'] = $last_moneylog_residue_money - abs($money);
                    $data['expenditure_money']=abs($money);
                    Moneylog::create($data);
                }
            }

        }else{
            $pay_type_name = $paytype[$pay_type_id] ?? '';
            $receipt = self::receiptType($pay_type_name);
            $data['type'] = $receipt['type'];
            $data['receipt_type'] = $receipt['receipt_type'];
            $receipt_type_name = $receipt['receipt_type_name'];

            $count_res = self::getmoneylogcount($data['type'], $data['receipt_type'], $cp_id);
            $receipt_no = $receipt_type_name . $count_res['no'];

            $data['inout_type'] = 2;
            $data['issys'] = 2;
            $data['abstract'] = $sn_code;
            $data['receipt_no'] = $receipt_no;
            $last_moneylog = Moneylog::where(['type' => $data['type'], 'store_id' => $store_id, 'is_del' => 1])->orderBy('id', 'desc')->first();
            $last_moneylog_residue_money = $last_moneylog ? $last_moneylog->residue_money : 0;
            $data['residue_money'] = $last_moneylog_residue_money - $expenditure_money;
            Moneylog::create($data);
        }

    }

    public static function createMoneyLogByPaymoneyAuditCancel($cp_id, $store_id, $pay_type_id, $expenditure_money, $sn_code, $subject_id = -2, $abstract = '应付账款')
    {
        $data = ['cp_id' => $cp_id,
            'store_id' => $store_id,
            'pay_type_id' => $pay_type_id,
            'income_money' => $expenditure_money,
            'expenditure_money' => 0,
            'log_date' => date('Y-m-d'),
            'subject_id' => $subject_id,
            'create_at' => time(),
            'update_at' => time()];
        $pay_type_name = PaytypeList::where(['id' => $pay_type_id])->value('paytype_name');
        if (strpos($pay_type_name, '现金') !== false) {
            $data['type'] = 1;
            $data['receipt_type'] = 2;
            $receipt_type_name = '现付';
        } else {
            if (strpos($pay_type_name, '储值') !== false) {
                $data['type'] = 3;
                $data['receipt_type'] = 0;
                $receipt_type_name = '储值卡';
            } else {
                $data['type'] = 2;
                $data['receipt_type'] = 3;
                $receipt_type_name = '银记';
            }

        }

        $count_res = self::getmoneylogcount($data['type'], $data['receipt_type'], $cp_id);
        $receipt_no = $receipt_type_name . $count_res['no'];

        $data['inout_type'] = 1;
        $data['issys'] = 2;
        $data['abstract'] = $sn_code;
        $data['receipt_no'] = $receipt_no;
        $last_moneylog = Moneylog::where(['type' => $data['type'], 'store_id' => $store_id, 'is_del' => 1])->orderBy('id', 'desc')->first();
        $last_moneylog_residue_money = $last_moneylog ? $last_moneylog->residue_money : 0;
        $data['residue_money'] = $last_moneylog_residue_money - $expenditure_money;
        Moneylog::create($data);
    }


    public static function createMoneyLogByTotalstockin($cp_id, $store_id, $income_money, $sn_code, $subject_id = -2, $abstract = '总库存付款')
    {
        $data = ['cp_id' => $cp_id, 'store_id' => $store_id, 'income_money' => $income_money, 'expenditure_money' => 0, 'log_date' => date('Y-m-d'), 'subject_id' => $subject_id, 'create_at' => time(), 'update_at' => time()];
        $data['type'] = 2;
        $data['receipt_type'] = 3;
        $receipt_type_name = '银记';

        $count_res = self::getmoneylogcount($data['type'], $data['receipt_type'], $cp_id);
        $receipt_no = $receipt_type_name . $count_res['no'];


        $data['inout_type'] = 2;
        $data['issys'] = 2;
        $data['abstract'] = $sn_code;
        $data['receipt_no'] = $receipt_no;
        $last_moneylog = Moneylog::where(['type' => $data['type'], 'store_id' => $store_id, 'is_del' => 1])->orderBy('id', 'desc')->first();
        $last_moneylog_residue_money = $last_moneylog ? $last_moneylog->residue_money : 0;
        $data['residue_money'] = $last_moneylog_residue_money + $income_money;
        Moneylog::create($data);
    }

    protected static function moneylogAdd($cp_id, $data, $store_id, $sn_code, $receipt_type_name, $income_money, $pay_type_id)
    {
        $count_res = self::getmoneylogcount($data['type'], $data['receipt_type'], $cp_id);
        $receipt_no = $receipt_type_name . $count_res['no'];
        $data['issys'] = 2;
        $data['abstract'] = $sn_code;
        $data['receipt_no'] = $receipt_no;
        $fee = self::getFeeByMoney($cp_id, $store_id, $income_money, $pay_type_id);
        $feedata = $data;
        $data['inout_type'] = 2;
        $last_moneylog = Moneylog::where(['type' => $data['type'], 'store_id' => $store_id, 'is_del' => 1])->orderBy('id', 'desc')->first();
        $last_moneylog_residue_money = $last_moneylog ? $last_moneylog->residue_money : 0;
        $data['residue_money'] = $last_moneylog_residue_money + $income_money;

        $feedata['inout_type'] = 1;
        if ($feedata['type'] == 1) {
            $feedata['receipt_type'] = 2;
            $receipt_type_name = '现付';
            $count_res = self::getmoneylogcount($feedata['type'], $feedata['receipt_type'], $cp_id);
            $receipt_no = $receipt_type_name . date('n') . '-' . ($count_res['count']) . '#';
        } else {
            $receipt_no = $receipt_type_name . date('n') . '-' . ($count_res['count'] + 1) . '#';
        }
        $feedata['receipt_no'] = $receipt_no;
        $feedata['abstract'] = $sn_code;
        $feedata['income_money'] = 0;
        $feedata['expenditure_money'] = $fee;
        $feedata['residue_money'] = $data['residue_money'] - $fee;
        $feedata['subject_id'] = -5;
        Moneylog::create($data);
        Moneylog::create($feedata);

        return true;
    }


    protected static function receiptType($pay_type_name='')
    {

        $data = [];
        if (strpos($pay_type_name, '现金') !== false) {
            $data['type'] = 1;
            $data['receipt_type'] = 1;
            $data['receipt_type_name'] = '现收';
        } else {
            if (strpos($pay_type_name, '储值') !== false) {
                $data['type'] = 3;
                $data['receipt_type'] = 0;
                $data['receipt_type_name'] = '储值卡';
            } else {
                $data['type'] = 2;
                $data['receipt_type'] = 3;
                $data['receipt_type_name'] = '银记';
            }
        }

        return $data;
    }
}
